﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WasaWasa.Controls;
using System.Net;
using System.Configuration;
using System.IO;
using Path = System.IO.Path;
using System.Reflection;

using Res = WasaWasa.Properties.Resources;

namespace WasaWasa
{
    /// <summary>
    /// SettingsWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class SettingsWindow : Window
    {
        Properties.Settings def = Properties.Settings.Default;

        Dictionary<Control, DependencyProperty> settingControls;

        public SettingsWindow()
        {
            InitializeComponent();
            InitializeSettingsControls();

            Resources["applicationSettings"] = def;
            Resources["versionInfo"] = new VersionInfoClass();
        }

        /// <summary>
        /// 設定にバインディングされているコントロールを列挙します。
        /// </summary>
        private void InitializeSettingsControls()
        {
            settingControls = new Dictionary<Control, DependencyProperty>();
            //全般
            settingControls.Add(chkIsUserIconVisible, CheckBox.IsCheckedProperty);
            settingControls.Add(numUserIconSize, NumericUpDown.ValueProperty);
            settingControls.Add(cbxFontFamily, ComboBox.SelectedItemProperty);
            settingControls.Add(numFontSize, NumericUpDown.ValueProperty);
            //ログイン
            settingControls.Add(txtUserName, TextBox.TextProperty);
            settingControls.Add(radUseBasicAuthentication, RadioButton.IsCheckedProperty);
            settingControls.Add(radUseWassrAuthenticationAPI, RadioButton.IsCheckedProperty);
            //プロキシ
            settingControls.Add(chkUseProxy, CheckBox.IsCheckedProperty);
            settingControls.Add(chkUseSystemProxy, CheckBox.IsCheckedProperty);
            settingControls.Add(txtProxyHost, TextBox.TextProperty);
            settingControls.Add(txtProxyPort, TextBox.TextProperty);
            settingControls.Add(txtProxyUserName, TextBox.TextProperty);
            //パフォーマンス
            settingControls.Add(numFriendsTimelineInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numRecentTimelineInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numPublicTimelineInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numSLTimelineInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numChannelTimelineInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numUserTimelineInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numFriendsListInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numFollowerListInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numFootprintsListInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numTODOInterval, NumericUpDown.ValueProperty);
            settingControls.Add(numFriendsTimelineCapacity, NumericUpDown.ValueProperty);
            settingControls.Add(numRecentTimelineCapacity, NumericUpDown.ValueProperty);
            settingControls.Add(numPublicTimelineCapacity, NumericUpDown.ValueProperty);
            settingControls.Add(numSLTimelineCapacity, NumericUpDown.ValueProperty);
            settingControls.Add(numChannelTimelineCapacity, NumericUpDown.ValueProperty);
            settingControls.Add(numUserTimelineCapacity, NumericUpDown.ValueProperty);
            //クロスポスト
            settingControls.Add(chkUseCrossPostToTwitter, CheckBox.IsCheckedProperty);
            settingControls.Add(txtTwitterUserName, TextBox.TextProperty);
            settingControls.Add(chkUseCrossPostToMogo2, CheckBox.IsCheckedProperty);
            settingControls.Add(txtMogo2UserName, TextBox.TextProperty);
            settingControls.Add(chkUseCrossPostToJaiku, CheckBox.IsCheckedProperty);
            settingControls.Add(txtJaikuUserName, TextBox.TextProperty);
            settingControls.Add(chkIsCrossPostUpdateToChannel, CheckBox.IsCheckedProperty);
            settingControls.Add(chkIsCrossPostReplyToStatus, CheckBox.IsCheckedProperty);
            settingControls.Add(chkIsCrossPostReplyToUser, CheckBox.IsCheckedProperty);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateSettingsBindingTargets();
        }

        /// <summary>
        /// 設定をターゲットに反映します。
        /// </summary>
        private void UpdateSettingsBindingTargets()
        {
            foreach (var item in settingControls)
            {
                try
                {
                    BindingOperations.GetBindingExpression(item.Key, item.Value).UpdateTarget();
                }
                catch(NullReferenceException)
                {
                    MessageBox.Show(item.ToString());
                }
            }
            try
            {
                txtPassword.Password = DESStringCrypto.DecryptString(def.Password);
                txtAuthenticationToken.Password = DESStringCrypto.DecryptString(def.AuthenticationToken);
                txtProxyPassword.Password = DESStringCrypto.DecryptString(def.ProxyPassword);
                txtTwitterPassword.Password = DESStringCrypto.DecryptString(def.TwitterPassword);
                txtMogo2Password.Password = DESStringCrypto.DecryptString(def.Mogo2Password);
                txtJaikuPassword.Password = DESStringCrypto.DecryptString(def.JaikuPassword);
            }
            catch
            {
                txtPassword.Password = "";
                txtAuthenticationToken.Password = "";
                txtProxyPassword.Password = "";
                txtTwitterPassword.Password = "";
                txtMogo2Password.Password = "";
                txtJaikuPassword.Password = "";
            }
        }

        /// <summary>
        /// ターゲットを設定に反映します。
        /// </summary>
        private void UpdateSettingsBindingSource()
        {
            foreach (var item in settingControls)
            {
                try
                {
                    BindingOperations.GetBindingExpression(item.Key, item.Value).UpdateSource();
                }
                catch(NullReferenceException)
                {
                    MessageBox.Show(item.ToString());
                }
            }
            def.Password = DESStringCrypto.EncryptString(txtPassword.Password);
            def.AuthenticationToken = DESStringCrypto.EncryptString(txtAuthenticationToken.Password);
            def.ProxyPassword = DESStringCrypto.EncryptString(txtProxyPassword.Password);
            def.TwitterPassword = DESStringCrypto.EncryptString(txtTwitterPassword.Password);
            def.Mogo2Password = DESStringCrypto.EncryptString(txtMogo2Password.Password);
            def.JaikuPassword = DESStringCrypto.EncryptString(txtJaikuPassword.Password);
        }

        private void btnApplySettings_Click(object sender, RoutedEventArgs e)
        {
            UpdateSettingsBindingSource();
        }

        private void btnSaveSettings_Click(object sender, RoutedEventArgs e)
        {
            UpdateSettingsBindingSource();
            def.Save();
        }

        private void btnLoadSettings_Click(object sender, RoutedEventArgs e)
        {
            def.Reload();
            UpdateSettingsBindingTargets();
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnGetAuthenticationToken_Click(object sender, RoutedEventArgs e)
        {
            AuthenticationWindow aw = new AuthenticationWindow();
            if (aw.ShowDialog() == true)
            {
                txtAuthenticationToken.Password = aw.AuthenticationToken;
            }
        }

        private void cleanupSettingsFileCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if(MessageBox.Show(Res.QuestionCleanupSettingsFile, Res.OperationCleanupSettingsFile, MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                return;
            string dirPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath)));
            string[] directorisToDelete = Directory.GetDirectories(dirPath, Path.GetFileName(Assembly.GetExecutingAssembly().Location) + "*");
            foreach (var dir in directorisToDelete)
            {
                Directory.Delete(dir, true);
            }
            UpdateSettingsBindingSource();
            def.Save();
        }
    }
}
